package edu.nf.test.demo02;

import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author CSY
 * @date 2025 - 04 - 16
 * 容器工厂
 */
public class ContainerFactory {
    /**
     * 容器
     */
    private final Map<String,Object> container = new HashMap<>();

    public ContainerFactory(String packageName) {
        init(packageName);
    }

    private void init (String packageName) {
        ClassInfoList list = ScanUtils.scan(packageName);
        for (ClassInfo classInfo : list) {
            Class<?> clazz = classInfo.loadClass();

            if (clazz.isAnnotationPresent(Component.class)){
                try {
                    String name = clazz.getAnnotation(Component.class).value();
                    Object instance = clazz.getConstructor().newInstance();
                    container.put(name,instance);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

    public <T> T getBean(String name) {
        if (container.containsKey(name)) {
            return (T) container.get(name);
        }
        throw new RuntimeException("不存在"+name);
    }
}
